﻿//-----------------------------------------------------------------------------
// Author: JCBDigger
// URL: http://Games.DiscoverThat.co.uk
//-----------------------------------------------------------------------------
// List control with buttons to change the order of the items in the list.
// Includes keyboard controls and mouse buttons.
// Use shift-up and shift-down arrows to move the items.
//-----------------------------------------------------------------------------

#region MIT License
/*
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Engine
{
    public partial class UpDownListControl : UserControl
    {
        public UpDownListControl()
        {
            InitializeComponent();
            SetDefaultProperties();
        }

        private void SetDefaultProperties()
        {
            TabIndex = 0;
            Visible = true;
            Enabled = true;
            ItemsList.SelectionMode = SelectionMode.One;
            // Press the Add button when the list control is double clicked
            ItemsList.MouseDoubleClick += new MouseEventHandler(list_DoubleClick);
            // Allow for holding down the ctrl or shift to move items
            ItemsList.KeyDown += new KeyEventHandler(list_KeyDown);
        }

        //////////////////////////////////////////////////////////////////////
        // == Properties ==
        //
        /// <summary>
        /// Add an EventHandler to the button.
        /// 
        /// Example: 
        /// UpDownListControl listControl = new UpDownListControl()
        /// listControl.ButtonAdd.Click += new EventHandler(ButtonAdd_Click);
        /// 
        /// private void ButtonAdd_Click(object sender, EventArgs e)
        /// {
        ///     Button btn = (System.Windows.Forms.Button)sender;
        ///     UpDownListControl list = (UpDownListControl)btn.Parent;
        ///     list.AddAndSelect("Test at: " + DateTime.Now.ToShortTimeString());
        /// }
        /// </summary>
        public System.Windows.Forms.Button ButtonAdd
        {
            get { return buttonAdd; }
        }

        private bool showRemoveWarning = true;
        /// <summary>
        /// By default a warning message is displayed every time the RemoveButton is pressed.
        /// </summary>
        public bool ShowRemoveWarning
        {
            get { return showRemoveWarning; }
            set { showRemoveWarning = value; }
        }

        /// <summary>
        /// Get or Set if the control is enabled
        /// </summary>
        public new bool Enabled
        {
            get { return base.Enabled; }
            set
            {
                base.Enabled = value;
                ItemsList.Enabled = value;
                buttonAdd.Enabled = value;
                buttonRemove.Enabled = value;
                buttonUp.Enabled = value;
                buttonDown.Enabled = value;
            }
        }

        /// <summary>
        /// Get or Set if the control is visible
        /// </summary>
        public new bool Visible
        {
            get { return base.Visible; }
            set
            {
                base.Visible = value;
                ItemsList.Visible = value;
                buttonAdd.Visible = value;
                buttonRemove.Visible = value;
                buttonUp.Visible = value;
                buttonDown.Visible = value;
            }
        }

        /// <summary>
        /// Get or Set if you can tab to this control
        /// </summary>
        public new bool TabStop
        {
            get { return base.TabStop; }
            set
            {
                base.TabStop = value;
                ItemsList.TabStop = value;
                buttonAdd.TabStop = value;
                buttonRemove.TabStop = value;
                buttonUp.TabStop = value;
                buttonDown.TabStop = value;
            }
        }

        /// <summary>
        /// Get the highest tab index used by the control or Set the lowest tab index to use for this control
        /// </summary>
        public new int TabIndex
        {
            get { return buttonDown.TabIndex; }
            set
            {
                TabStop = true;
                base.TabIndex = value;
                ItemsList.TabIndex = base.TabIndex + 1;
                buttonAdd.TabIndex = ItemsList.TabIndex + 1;
                buttonRemove.TabIndex = buttonAdd.TabIndex + 1;
                buttonUp.TabIndex = buttonRemove.TabIndex + 1;
                buttonDown.TabIndex = buttonUp.TabIndex + 1;
            }
        }

        public int SelectedIndex
        {
            get { return ItemsList.SelectedIndex; }
            // Use SetSelected so that the highlighted text and the index are in the same place when moved about
            set
            {
                if (ItemsList.Items.Count < 1)
                {
                    // This is needed to avoid errors in the form designer when the list is empty
                    return;
                }
                if (value < 0 || ItemsList.Items.Count < 1)
                {
                    ItemsList.SetSelected(-1, false);
                }
                else if (value >= 0 && value < ItemsList.Items.Count)
                {
                    ItemsList.SetSelected(value, true);
                }
                else
                {
                    ItemsList.SetSelected(ItemsList.Items.Count - 1, true);
                }
            }
        }
        //
        //////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////
        // == Setup and Change ==
        //
        public void Add(string thing)
        {
            if (string.IsNullOrEmpty(thing))
            {
                return;
            }
            ItemsList.Items.Add(thing);
        }

        public void AddAndSelect(string thing)
        {
            if (string.IsNullOrEmpty(thing))
            {
                return;
            }
            Add(thing);
            SetSelectedToTheEnd();
        }

        public void AddRange(List<string> things)
        {
            if (things == null || things.Count < 1)
            {
                return;
            }
            ItemsList.Items.AddRange(things.ToArray());
        }

        public void InsertAt(int index, string thing)
        {
            if (string.IsNullOrEmpty(thing))
            {
                return;
            }
            if (index >= ItemsList.Items.Count || ItemsList.Items.Count < 1)
            {
                Add(thing);
                return;
            }
            if (index < 0)
            {
                ItemsList.Items.Insert(0, thing);
                return;
            }
            ItemsList.Items.Insert(index, thing);
        }

        public void RemoveAt(int index)
        {
            if (index >= ItemsList.Items.Count || index < 0)
            {
                return;
            }
            ItemsList.Items.RemoveAt(index);
        }

        /// <summary>
        /// Up reduced the index towards zero /\
        /// </summary>
        public void MoveUpFrom(int index)
        {
            if (index < 1 || index >= ItemsList.Items.Count || ItemsList.Items.Count < 2)
            {
                return;
            }
            string thing = (string)ItemsList.Items[index - 1];
            RemoveAt(index - 1);
            // Remember we have removed one item
            InsertAt(index, thing);
            SelectedIndex = index - 1;
        }

        /// <summary>
        /// Down increases the index \/
        /// </summary>
        public void MoveDownFrom(int index)
        {
            if (index < 0 || index >= ItemsList.Items.Count - 1 || ItemsList.Items.Count < 2)
            {
                return;
            }
            string thing = (string)ItemsList.Items[index + 1];
            RemoveAt(index + 1);
            InsertAt(index, thing);
            SelectedIndex = index + 1;
        }

        public void MoveUpSelected()
        {
            MoveUpFrom(ItemsList.SelectedIndex);
        }

        public void MoveDownSelected()
        {
            MoveDownFrom(ItemsList.SelectedIndex);
        }

        public void SetSelectedToTheEnd()
        {
            if (ItemsList.Items.Count > 0)
            {
                ItemsList.SetSelected(ItemsList.Items.Count - 1, true);
            }
        }

        public void ClearSelection()
        {
            if (ItemsList.Items.Count > 0)
            {
                ItemsList.SetSelected(-1, false);
            }
        }
        //
        //////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////
        // == Results ==
        //
        public List<string> GetItems()
        {
            List<string> result = new List<string>();
            for (int r = 0; r < ItemsList.Items.Count; r++)
            {
                result.Add((string)ItemsList.Items[r]);
            }
            return result;
        }
        //
        //////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////
        // == Internal functions ==
        //
        private void buttonUp_Click(object sender, EventArgs e)
        {
            MoveUpSelected();
        }

        private void buttonDown_Click(object sender, EventArgs e)
        {
            MoveDownSelected();
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            int index = ItemsList.SelectedIndex;
            if (index < 0)
            {
                return;
            }
            if (!showRemoveWarning || RemoveAreYouSure((string)ItemsList.Items[index]))
            {
                RemoveAt(index);
                SelectedIndex = index;
            }
        }

        private bool RemoveAreYouSure(string thing)
        {
            if (MessageBox.Show(
                "Are you sure you want to remove the following?\n\n" + thing,
                "Remove From The List?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Information) == DialogResult.Yes)
            {
                return true;
            }
            return false;
        }
        //
        //////////////////////////////////////////////////////////////////////

        //////////////////////////////////////////////////////////////////////
        // == Capture keys and mouse events ==
        //
        private void list_DoubleClick(object sender, EventArgs e)
        {
            buttonAdd.PerformClick();
        }

        private void list_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Modifiers & Keys.Shift) != 0)
            {
                if (e.KeyCode == Keys.Up)
                {
                    MoveUpSelected();
                    // Prevent the default key action
                    e.Handled = true;
                }

                if (e.KeyCode == Keys.Down)
                {
                    MoveDownSelected();
                    // Prevent the default key action
                    e.Handled = true;
                }
            }

        }
        //
        //////////////////////////////////////////////////////////////////////
    }
}
